package com.antfinancial.antchain.smallprogram.controller;
import com.antfinancial.antchain.smallprogram.Response.LotteryResult;
import com.antfinancial.antchain.smallprogram.service.BlockchainService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping(value = "/api")
public class MainController {
    private static Logger logger= LoggerFactory.getLogger(MainController.class);
    @Autowired
    private BlockchainService blockchainService;
    @RequestMapping(value = "/test")
    public Map test(){
        Map<String,Object> result=new HashMap<>();
        result.put("result","success");
        return result;
    }
    @RequestMapping("/lottery")
    public List lottery(long number,HttpServletResponse response)throws Exception{
        if(number<=6){
            response.setStatus(400);
            response.setHeader("content-type","application/json;charset=UTF-8");
            response.getOutputStream().write("{\"message\":\"人数不能小于6个\"}".getBytes("utf-8"));
            return null;
        }
        Timestamp createTime=new Timestamp(System.currentTimeMillis());
        HashSet<Long> alreadyLuckers=new HashSet<>();
        List<LotteryResult> lotteryResults=new ArrayList<>();
        int round=0;
        while(round<3){
            int i=0;
            while(i<=0){
                Long luck=(long)(number*Math.random());
                if(!alreadyLuckers.contains(luck)){
                    String txHash=blockchainService.callMethod(luck,1,createTime);
                    lotteryResults.add(LotteryResult.builder().id(luck).level(round+1).createTime(createTime).txHash(txHash).build());
                    alreadyLuckers.add(luck);
                    i++;
                }
            }
            round++;
        }
        return lotteryResults;
    }
}
